<?php

declare(strict_types=1);

namespace sheep\channel;

use think\Model;
use think\facade\Log;
use think\facade\Validate;
use yunwuxin\Notification;
use yunwuxin\notification\Channel;
use yunwuxin\notification\Notifiable;
use sheep\library\mail\Mail;

class Email extends Channel
{

    public function __construct()
    {
    }


    /**
     * 发送邮件通知
     * 
     * @param Notifiable   $notifiable
     * @param Notification $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        $params = $this->getMessage($notifiable, $notification);

        if ($params && isset($notifiable['email']) && Validate::is($notifiable['email'], "email")) {
            try {
                $email = new Mail;
                $result = $email->addAddress($notifiable['email'], $notifiable['nickname'])
                    ->setSubject(($params['data'] ? $params['data']['template'] : '邮件通知'))
                    ->setBody('<div style="min-height:550px; padding: 50px 20px 100px;">' . $params['content'] . '</div>')
                    ->send();

                if ($result) {
                    // 发送成功
                    $notification->sendOk('Email');
                } else {
                    // 邮件发送失败
                    Log::error('邮件消息发送失败：用户：' . $notifiable['id'] . '；类型：' . get_class($notification) . "；发送类型：" . $notification->event . "；错误信息：" . json_encode($result, JSON_UNESCAPED_UNICODE));
                }
            } catch (\Exception $e) {
                // 因为配置较麻烦，这里捕获异常防止因为缺少字段，导致队列一直执行不成功
                Log::error('邮件消息发送失败，捕获异常：用户：' . $notifiable['id'] . '；类型：' . get_class($notification) . "；发送类型：" . $notification->event . "；错误信息：" . $e->getMessage());
            }

            return true;
        }

        // email
        Log::error('邮件消息发送失败，没有 email，或 email 格式不正确：用户：' . $notifiable['id'] . '；类型：' . get_class($notification) . "；发送类型：" . $notification->event);

        return false;
    }
}
